import numpy as np
import cv2
from collections import OrderedDict
import math
def addItems(items,item):
    item=(item[0],item[1],item[2])
    if item in items.keys():
        items[item]+=1
    else:
        items[item]=1
    return items
def sort_value(old_dict, reverse=False):
    """对字典按 value 排序, 默认升序, 不修改原先字典"""
    # 获取按 value 排序后的元组列表
    items = sorted(old_dict.items(), key=lambda obj: obj[1], reverse=reverse)
    # 创建一个新的空字典
    new_dict = OrderedDict()
    # 遍历 items 列表
    for item in items:
        # item[0] 存的是 key 值
        new_dict[item[0]] = old_dict[item[0]]
    return new_dict
#除背景
def background():
    raw_img = cv2.imread(filename=r"images/lemon.jpg")
    # cv2.imshow("damaged image", img)
    # cv2.waitKey(0)
    # raw_img=img.copy() 
    # get the shape of the image
    height, width = raw_img.shape[0], raw_img.shape[1]
     
    #将所有点的颜色放入字典{颜色：数量}
    colors=OrderedDict()
    for i in range(height):
        for j in range(width):
            addItems(colors,raw_img[i, j])
    #按颜色数量排序
    colors=sort_value(colors)
    print(colors)
    #取数量最多的14个颜色
    max_keys=list(colors.keys())[-14:]
    #求最多颜色的平均值
    max_key=getAverage(max_keys)
    # for one in colors.keys():
    #     print(one,max_key,jl(one,max_key))
    #与最多颜色比较，距离<70的抹去
    for i in range(height):
        for j in range(width):
            p=(raw_img[i, j][0],raw_img[i, j][1],raw_img[i, j][2])
            if jl(p,max_key)<70:
                raw_img[i, j] = 0
            else:
            	pass
    #输出
    cv2.imwrite("out.jpg",raw_img)
#计算颜色平均值
def getAverage(l):
	r=[0.0,0.0,0.0]
	ct=0.0
	for one in l:
		r[0]=r[0]+one[0]
		r[1]=r[1]+one[1]
		r[2]=r[2]+one[2]
		ct+=1
	return(r[0]/ct,r[1]/ct,r[2]/ct)
#计算两个颜色之间距离
def jl(p1,p2):
    # print(p1,p2)
    t=(math.pow(float(p1[0])-float(p2[0]),2)+math.pow(float(p1[1])-float(p2[1]),2)+math.pow(float(p1[2])-float(p2[2]),2))
    return math.sqrt(t)
background()